/*
* @Date: 2020/11/10
* @Author: XueChengwu <xuechengwu@erayt.com>
* @Copyright: 2015-2019 Erayt, Inc.
* @Description: If you have some questions, please contact: xuechengwu@erayt.com.
*/
/**
 * 页面缓存装饰器，页面保存在sessionStorage
 * @param key
 * @param callback
 * @returns {Function}
 */
export default function alive(key, saveFunc, exportFunc) {
  return (target) => {
    const unMounted = target.prototype.componentWillUnmount;
    target.prototype.componentWillUnmount = function() {
      // 将状态缓存
      saveFunc && saveFunc(this);
      sessionStorage.setItem(key, JSON.stringify(this.state));
      unMounted && unMounted.apply(this);
    };
    const willMounted = target.prototype.componentWillMount;
    target.prototype.componentWillMount = function() {
      // 将状态从缓存中提取
      let state = sessionStorage.getItem(key);
      if (state) {
        state = JSON.parse(state);
        exportFunc && (state = exportFunc(this, state));
        Object.assign(this.state, state);
      }
      // 清理sessionStorage
      sessionStorage.removeItem(key);
      willMounted && willMounted.apply(this);
    };
  };
}
